const baseUnit = 100;
var phi = 0;
var camidx = 0;
var uuid = "";
var filepath = "";
var filelist = "";
var subjectCollection = [];
var subjectSelectCurrent = null;
var subjectSelectTop= 0;//科目选择器top值
var containerBodyScrollTop = 0;
var functionalKeyArray = [9, 20, 13, 16, 17, 18, 91, 92, 93, 45, 36, 33, 34, 35, 37, 39, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 144, 19, 145, 40, 38, 27];//键盘上功能键键值数组
var subjectInputText = null;
$(function () {
    balanceColor();//设置余额字体颜色
    var voucherTable = $(".voucher-flex-container");
    const max = 999999999.99;//
    //请求科目集合
    requestSubject();
    let scrollWidth = scrollWidthFun();
    $(".scroll-bar-col").width(scrollWidth);
    $(window).keydown(function (event) {
        if ((event.which === 83 && event.ctrlKey)) {
            console.log("Ctrl-s 保存");
            let cla = GetQueryString("cla");
            if (cla ==='voucherModel'){
                subForm('voucherForm', root + 'control/adIndex.html?cla=voucherModel&fun=templateEdit')
            }else{
                subForm('voucherForm', root + 'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=save')
            }

            return false;
        }
        if ((event.altKey && event.which === 78)) {
            let cla = GetQueryString("cla");
            console.log("alt+N 新增");
            if (cla ==='voucherModel'){
                location.href = root + 'control/adIndex.html?cla=voucherModel&fun=home';
            }else{
                location.href = root + 'control/adIndex.html?cla=voucherEdit&fun=home';
            }

            return false;
        }
        if (event.which === 123) {
            event.preventDefault();
            let cla = GetQueryString("cla");
            if (cla ==='voucherModel'){
                return false;
            }
            subForm('voucherForm', root + 'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=new');
            console.log("F12 保存并新增");
            return false;
        }
        if (event.which === 120) {
            event.preventDefault();
            console.log("F9 保存并复制");
            let cla = GetQueryString("cla");
            if (cla ==='voucherModel'){
                return false;
            }
            subForm('voucherForm', root + 'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=copy');
            return false;
        }
        if (event.which === 9) {
            event.preventDefault();
        }
    });
    $(window).resize(function () {
        hideSelector();
        hideCurrency();
        hideAssetSelector();
    });
    $(".container-body").scroll(function () {
        let scrollTop = $(this).scrollTop();
        let subjectSelector = $(".subject-selector");
        let bigAutocompleteContent = $("#bigAutocompleteContent");
        let auxiliary = $(".auxiliary-accounting");
        let currencyAssit = $(".currency-assit");
        if (subjectSelector.css('display') == 'block'){
            subjectSelector.css({"top": subjectSelectTop-scrollTop});
        }
        if (bigAutocompleteContent.css('display') == 'block'){
            let offset = bigAutocompleteContent.offset().top-39;
            bigAutocompleteContent.css({"top": offset-scrollTop+containerBodyScrollTop});
        }
        if (auxiliary.css('display') == 'block'){
            let offset = auxiliary.offset().top-39;
            auxiliary.css({"top": offset-scrollTop+containerBodyScrollTop});
        }
        if (currencyAssit.css('display') == 'block'){
            let offset = currencyAssit.offset().top-39;
            currencyAssit.css({"top": offset-scrollTop+containerBodyScrollTop});
        }
        containerBodyScrollTop = scrollTop;
    })
    $(document).bind('mousedown', function (event) {
        var $target = $(event.target);
        if ((!($target.parents().andSelf().is('.subject-selector'))) && (!$target.is(subjectSelectCurrent))) {
            hideSelector()
        }
        // if (!($target.parents().andSelf().is('.auxiliary-accounting')) && (!($target.parents().andSelf().is('#bigAutocompleteContent')))) {
        //     hideAssetSelector()
        // }
    });
    $(".subject-selector").on('click', '.subject-item', function () {
        subjectItemCallback($(this));
    })
    $("#shortKey").hover(function () {

    }, function () {
        $(".shortcut-key-content").hide();
    })
    $("#shortKey").click(function () {
        $(".shortcut-key-content").show();
    })
    //点击科目分类
    $(".subject-tabs").on('click','.tab-item', function () {
        let _this = $(this);
        if (_this.hasClass('active')) {
            return false;
        } else {
            _this.addClass('active').siblings().removeClass('active');
            let data = [];
            switch (_this.html()) {
                case '全部':
                    data = subjectCollection.all;
                    break;
                case '资产':
                    data = subjectCollection.asset;
                    break;
                case '负债':
                    data = subjectCollection.debt;
                    break;
                case '权益':
                    data = subjectCollection.interests;
                    break;
                case '成本':
                    data = subjectCollection.cost;
                    break;
                case '损益':
                    data = subjectCollection.loss;
                    break;
                case '共同':
                    data = subjectCollection.common;
                    break;
            }
            readySubject(subjectSelectCurrent.val(), data)
        }
    })

    //点击非下拉区域隐藏
    $(document).on('click', function (e) {
        let target = $("#text-btn");
        if (!target.is(e.target) && target.has(e.target).length === 0) {
            $("#text-input").hide();
        }
    });
    $("#next-button,#pre-button").on('click', function () {
        let type = $(this).data('type');
        let id = $(this).data('id');
        let voucherWordId = $("[name='voucherWordId']").val();
        let voucherNo = $("[name='voucherNo']").val();
        let recordDate = $("[name='recordDate']").val();
        $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=showNextVoucher', {
            type: type,
            id: id,
            voucherWordId: voucherWordId,
            voucherNo: voucherNo,
            recordDate: recordDate
        }, function (res) {
            if (res.warn === 2) {
                location.href = res.href;
            } else {
                msg(res.warn, 'error');
            }
        }, 'json')
    })

    //摘要文本补充
    $(".container-body .summary-col .summary-input").each(function () {
        $(this).bigAutocomplete({
            sign: 'voucherSummary',
            body: 'voucher-body',
            markPage: 'voucherEdit',//特殊页面
            url: root + 'control/adIndex.html?cla=voucherEdit&fun=getSummary',
            callback: function (data, e) {
                $(e).val(data.title);
                $(e).parent().find(".summary").text(data.title);
                //触发切换列
                enterFoucus($(e).parent().find(".summary"), 1)
            }
        });
    })

    /**
     * 科目栏获取焦点
     */
    voucherTable.off('click', '.container-body .subject-col').on('click', '.container-body .subject-col', function () {
        let _this = $(this);
        let mxId = _this.parent().find("[name='mxId[]']").val();
        let khid = _this.find("[name='khid["+mxId+"]']").val();
        let supplierId = _this.find("[name='supplierId["+mxId+"]']").val();
        let staffId = _this.find("[name='staffId["+mxId+"]']").val();
        let projectId = _this.find("[name='projectId["+mxId+"]']").val();
        let materialId = _this.find("[name='materialId["+mxId+"]']").val();
        let cashId = _this.find("[name='cashId["+mxId+"]']").val();
        let departmentId = _this.find("[name='departmentId["+mxId+"]']").val();
        // _this.find(".subject-content").hide();
        _this.find(".subject-input").show();
        _this.find(".subject-input").focus().select();
        if (departmentId || khid || supplierId || staffId || projectId || materialId || cashId){
            let subjectId = _this.find("[name='subjectId[" + mxId + "]']").val();
            showAssetSelector(_this.find(".subject-content"), {
                mxId: mxId,
                subjectId: subjectId,
                khid: khid,
                supplierId: supplierId,
                departmentId: departmentId,
                materialId: materialId,
                staffId: staffId,
                cashId: cashId,
                projectId: projectId
            })
        }else{
            selector(_this);
        }
        switchFoucus(_this.find(".subject-content"), 2);
    })
    /**
     * 科目栏失去焦点
     */
    voucherTable.on('blur', '.subject-input', function (e) {
        $(".voucher-body").off('keyup', ".subject-input");
        $(this).hide();
        let cell = $(this).parent().parent();
        let mxId = cell.parent().find("[name='mxId[]']").val();
        if (!cell.find("[name='subjectId["+mxId+"]']").val()){
            //如果科目删除则隐藏余额项
            cell.find(".balance").hide();
        }
        cell.find(".subject-name").text($(this).val())
        cell.find(".subject-content").show();
    })
    /**
     * 增加一行
     */
    voucherTable.on('click', '.add_v_btn', function () {
        let _this = $(this);
        $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=addRow', {}, function (res) {
            _this.parent().parent().after(res.html);
            listCol();
            scrollBottom();
        }, 'json')
    })
    /**
     * 删除一行
     */
    voucherTable.on('click', '.del_v_btn', function () {
        $(this).parent().parent().remove();
        if ($(".container-body .container-body-row").length < 12){
            $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=addRow', {}, function (res) {
                $(".container-body").append(res.html);
                listCol();
            }, 'json')
        }else{
            listCol();
        }
        total_money();
    })
    /**
     * 增加一行
     */
    voucherTable.on('click', '.copy_v_btn', function () {
        let _this = $(this);
        let row = _this.parent().parent();
        let mxId = row.find("[name='mxId[]']").val();
        row.after(row.clone());
        let randId = randomString(14);
        row.next().find("[name='mxId[]']").attr('data-id',randId);
        row.next().find("[name='mxId[]']").attr('value',randId);
        row.next().find("[name='summary["+mxId+"]']").attr('name',"summary["+randId+"]");
        row.next().find("[name='subjectId["+mxId+"]']").attr('name',"subjectId["+randId+"]");
        row.next().find("[name='khid["+mxId+"]']").attr('name',"khid["+randId+"]");
        row.next().find("[name='supplier["+mxId+"]']").attr('name',"supplier["+randId+"]");
        row.next().find("[name='staffId["+mxId+"]']").attr('name',"staffId["+randId+"]");
        row.next().find("[name='projectId["+mxId+"]']").attr('name',"projectId["+randId+"]");
        row.next().find("[name='materialId["+mxId+"]']").attr('name',"materialId["+randId+"]");
        row.next().find("[name='cashId["+mxId+"]']").attr('name',"cashId["+randId+"]");
        row.next().find("[name='departmentId["+mxId+"]']").attr('name',"departmentId["+randId+"]");
        row.next().find("[name='voucherMoney["+mxId+"]']").attr('name',"voucherMoney["+randId+"]");
        row.next().find("[name='currencyId["+mxId+"]']").attr('name',"currencyId["+randId+"]");
        row.next().find("[name='voucherPrice["+mxId+"]']").attr('name',"voucherPrice["+randId+"]");
        row.next().find("[name='voucherNum["+mxId+"]']").attr('name',"voucherNum["+randId+"]");
        row.next().find("[name='voucherRate["+mxId+"]']").attr('name',"voucherRate["+randId+"]");
        row.next().find("[name='jieMoney["+mxId+"]']").attr('name',"jieMoney["+randId+"]");
        row.next().find("[name='daiMoney["+mxId+"]']").attr('name',"daiMoney["+randId+"]");
        listCol();
        row.next().find(".summary-input").each(function() {
            $(this).bigAutocomplete({
                // width:543,
                body: 'voucher-body',
                sign:'voucherSummary',
                markPage: 'voucherEdit',//特殊页面
                url:root + 'control/adIndex.html?cla=voucherEdit&fun=getSummary',
                callback:function(data,e){
                    $(e).val(data.title);
                    $(e).parent().find(".summary").text(data.title);
                    //触发切换列
                    enterFoucus($(e).parent().find(".summary"),1)
                }
            });
        })
    })
    /**
     * 摘要 获取焦点输入
     */
    voucherTable.off('click', '.summary').on('click', '.summary', function (ev) {
        hideAssetSelector();
        hideCurrency();
        let _this = $(this);
        $(this).hide();
        let summaryInput = $(this).parent().find(".summary-input");
        summaryInput.show();
        summaryInput.focus().select();

        switchFoucus(_this, 1);
    })
    /**
     * 摘要 失去焦点
     */
    voucherTable.on('blur', '.summary-input', function () {
        $(this).hide();
        $(this).parent().find(".summary").text($(this).val())
        $(this).parent().find(".summary").show();
    })


    voucherTable.off('keydown', '.jie-input, .dai-input').on('keydown', ".jie-input, .dai-input", function (ev) {
        switch (ev.keyCode) {
            case 107:
            case 106:
            case 111:
                //加乘除
                ev.preventDefault();
                break;
            default:
                break;
        }
    })
    /**
     * 借方获取焦点
     */
    voucherTable.off('click', '.jie').on('click', ".jie", function () {
        hideCurrency();
        hideAssetSelector();
        hideSelector();
        let parent = $(this).parent();
        $(this).hide();
        parent.find(".money-input").show();
        parent.find(".money-input").focus().select();
        let _this = $(this);
        parent.find(".jie-input").off('keyup').keyup(function (ev) {
            let _that = $(this);
            let money = _that.val();
            _that.val(moneyCheck(_that.val()))
            switch (ev.keyCode) {
                case 9:
                    //Tab键
                    switchFoucus(_this, 3);
                    break;
                case 13:
                    //回车
                    autoAddRow(_this, _that, '借')
                    break;
                case 32:
                    //空格
                    spaceSwitch(_this, 'jie')
                    break;
                case 107:
                case 106:
                case 111:
                    //加乘除
                    ev.preventDefault();
                    let mxId = _this.parent().parent().find("[name='mxId[]']").val();
                    layer('voucherEdit', 'calculator', {mxId: mxId, money: money, type: 'jie'})
                    break;
                case 187:
                    // 自动平衡借贷方金额
                    let daiMoney = 0;
                    $(".dai-input").each(function () {
                        daiMoney += Number($(this).val());
                    });
                    let jieMoney = 0;
                    $(".jie-input").each(function () {
                        jieMoney += Number($(this).val());
                    });
                    let jie = Number(_that.val());
                    _that.val(daiMoney - jieMoney + jie);
                    splitNumber(((daiMoney - jieMoney + jie) * baseUnit).toFixed(0),parent.find(".jie-text"));
                    break;
                default:
                    if (!functionalKeyArray.includes(ev.keyCode)) {
                        parent.next().find(".dai-input").val('');
                        total_money();
                        splitNumber('',parent.next().find(".dai-text"))
                    }
                    break;
            }
        });
    })

    /**
     * 借方失去焦点
     */
    voucherTable.on('blur', ".jie-input", function () {
        let money = Number($(this).val());
        if (money > max) {
            msg('金额超过最大限制位数', 'error')
            return '';
        }
        $(this).hide();
        let cell = $(this).parent();
        cell.find(".show_money").show();
        splitNumber(money!=0?(money * baseUnit).toFixed(0):'',cell.find(".jie-text"))
        let daiMoney = Number(cell.next().find(".dai-input").val());
        if (money == 0 && daiMoney != 0) {
            return '';
        }
        cell.next().find(".dai-input").val('');
        total_money();
        splitNumber('',cell.next().find(".dai-text"))
        let row = $(this).parent().parent();
        let mxId = row.find("[name='mxId[]']").val();
        reverseCheck(row,mxId,money)//反向核算
        let subjectId = row.find("[name='subjectId[" + mxId + "]']").val();
        culBalance(subjectId, mxId);
    })

    /**
     * 贷方获取焦点
     */
    voucherTable.off('click', '.dai').on('click', ".dai", function () {
        hideCurrency();
        hideAssetSelector();
        hideSelector();
        let parent = $(this).parent();
        $(this).hide();
        let _this = $(this);
        parent.find(".money-input").show();
        parent.find(".money-input").focus().select();
        parent.find(".dai-input").off('keyup').keyup(function (ev) {
            let _that = $(this);
            let money = _that.val();
            _that.val(moneyCheck(_that.val()))
            switch (ev.keyCode) {
                case 9:
                    //Tab键
                    switchFoucus(_this, 4);
                    break;
                case 13:
                    //回车
                    autoAddRow(_this, _that, '贷');
                    break;
                case 32:
                    //空格
                    spaceSwitch(_this, 'dai')
                    break;
                case 107:
                case 106:
                case 111:
                    //加号
                    let mxId = _this.parent().parent().find("[name='mxId[]']").val();
                    layer('voucherEdit', 'calculator', {mxId: mxId, money: money, type: 'dai'})
                    break;
                case 187:
                    //等号
                    let daiMoney = 0;
                    $(".dai-input").each(function () {
                        daiMoney += Number($(this).val());
                    });
                    let jieMoney = 0;
                    $(".jie-input").each(function () {
                        jieMoney += Number($(this).val());
                    });
                    let dai = Number(_that.val());
                    _that.val(jieMoney - daiMoney + dai);
                    splitNumber(((jieMoney - daiMoney + dai) * baseUnit).toFixed(0),parent.find(".dai-text"))
                    break;
                default:
                    if (!functionalKeyArray.includes(ev.keyCode)) {
                        splitNumber('',parent.prev().find(".jie-text"));
                        parent.prev().find(".jie-input").val('');
                        total_money();

                    }
                    break;
            }
        });
    })
    /**
     * 贷方失去焦点
     */
    voucherTable.on('blur', ".dai-input", function () {
        let money = $(this).val();
        if (money > max) {
            msg('金额超过最大限制位数', 'error')
            return false;
        }
        $(this).hide();
        let cell = $(this).parent();
        splitNumber(money!=0?(money * baseUnit).toFixed(0):'',cell.find(".dai-text"))
        cell.find(".show_money").show();
        let jieMoney = Number(cell.prev().find(".jie-input").val());
        if (money == 0 && jieMoney != 0) {
            return false;
        }
        splitNumber('',cell.prev().find(".jie-text"));
        cell.prev().find(".jie-input").val('');
        total_money();

        let row = $(this).parent().parent();
        let mxId = row.find("[name='mxId[]']").val();
        reverseCheck(row,mxId,money)//反向核算
        let subjectId = row.find("[name='subjectId[" + mxId + "]']").val();
        culBalance(subjectId, mxId);
    })


    /**
     * 数量/外币列获取焦点
     */
    voucherTable.on('click', ".num-col", function () {
        let mxId = $(this).parent().find("[name='mxId[]']").val();
        let num = Number($(this).find("[name='voucherNum["+mxId+"]']").val());
        let currencyId = $(this).find("[name='currencyId["+mxId+"]']").val();
        let subjectId = $(this).parent().find("[name='subjectId["+mxId+"]']").val();
        if (num !=0 || currencyId){
            let price = Number($(this).find("[name='voucherPrice["+mxId+"]']").val());
            let rate = Number($(this).find("[name='voucherRate["+mxId+"]']").val());
            let money = Number($(this).find("[name='voucherMoney["+mxId+"]']").val());
            showCurrency($(this),{
                mxId:mxId,
                subjectId: subjectId,
                num:num,
                price:price,
                currencyId:currencyId,
                money:money,
                rate:rate,
            })
        }
    })
    $("#text-btn").on('click', function () {
        $("#text-input").show();
    })
    $("#text-input").on('blur', function () {
        $("#text-input").hide();
    })
})

/**
 * 反向核算
 * @param row
 * @param mxId
 * @param money
 */
function reverseCheck(row,mxId,money) {
    let rateRule = $(".calendarBody").data('r');//原币汇率反算规则
    let numRule = $(".calendarBody").data('n');//单价数量反算规则
    //计算单价
    let num = Number(row.find("[name='voucherNum[" + mxId + "]']").val());
    let price = Number(row.find("[name='voucherPrice[" + mxId + "]']").val());
    let rate = Number(row.find("[name='voucherRate[" + mxId + "]']").val());
    rate = rate !=0 ?rate:1;
    if (num > 0 && numRule ==='price') {
        //反算单价
        let price = (money/rate / num).toFixed(4);
        row.find("[name='voucherPrice[" + mxId + "]']").val(price)
        row.find(".voucher-price-text").html(price)
    }else if(price > 0 && numRule ==='num'){
        //反算数量
        let num = (money/rate / price).toFixed(2);
        row.find("[name='voucherNum[" + mxId + "]']").val(num)
        row.find(".voucher-num-text").html(num)
    }
    let currencyId = row.find("[name='currencyId[" + mxId + "]']").val();
    let voucherMoney = Number(row.find("[name='voucherMoney[" + mxId + "]']").val());
    if (currencyId){
        if (rateRule === 'money'){
            //反算原币
            voucherMoney = (money / rate).toFixed(2);
            row.find("[name='voucherMoney[" + mxId + "]']").val(voucherMoney)
            row.find(".voucher-money-text").html(voucherMoney)
        }else if(rateRule === 'rate'){
            //反算汇率
            rate = (money / voucherMoney).toFixed(4);
            row.find("[name='voucherRate[" + mxId + "]']").val(rate)
            row.find(".voucher-rate-text").html(rate)
        }
    }
}

/**
 * 空格切换借贷
 * @param _this
 * @param type
 */
function spaceSwitch(_this, type) {
    if (type === 'jie') {
        _this.parent().find(".jie-input").trigger('blur');
        _this.parent().parent().find(".dai").trigger('click')
    } else {
        _this.parent().parent().find(".dai-input").trigger('click')
        _this.parent().parent().find(".jie").trigger('click')
    }
}

function enterFoucus(_this, col, nextCol = 0) {
    switch (col) {
        case 1:

            let summaryInput = _this.parent().find(".summary-input");
            summaryInput.trigger('blur');
            //Tab键切换焦点
            _this.parent().parent().find(".subject-col").trigger('click')

            break;
        case 2:
        case 'subject':
            let subjectInput = _this.parent().find(".subject-input");
            subjectInput.trigger('blur');
            //Tab键切换焦点
            let jie = _this.parent().parent().find(".jie")
            jie.trigger('click');
            $("#bigAutocompleteContent").find("tr").removeClass("ct");
            $("#bigAutocompleteContent").hide();
            break;
        case 'jie-currency'://外币核算后触发到借方
            _this.find(".jie").trigger('click');
            break;
        case 'dai-currency'://外币核算后触发到贷方
            _this.find(".dai").trigger('click');
            break;
        case 3:
            _this.parent().find(".jie-input").trigger('blur');
            if (nextCol > 0) {
                autoFoucusNextCol(_this);
            } else {
                //Tab键切换焦点
                _this.parent().parent().find(".dai").trigger('click')
            }
            break;
        case 'currency':
            _this.parent().parent().find(".jie").trigger('click');
            break;
        default:
            _this.parent().find(".dai-input").trigger('blur');
            //Tab键切换焦点
            autoFoucusNextCol(_this);
            break;
    }
}

/**
 * 自动聚焦下一行
 * @param _this
 */
function autoFoucusNextCol(_this) {
    //1、判断是否还有下一行
    if (!_this.parent().parent().nextAll(".container-body-row").eq(0).hasClass("container-body-row")) {
        //没有下一行就自动新增一行
        addTr(_this);
    } else {

        _this.parent().parent().nextAll(".container-body-row").eq(0).find(".summary").trigger('click');
    }
}

function handleTextareaKeyPress(event) {
    if (event.keyCode === 13 && !event.ctrlKey) {
        event.preventDefault();
        // 在此处执行单独的回车键操作，例如提交评论
    } else if (event.keyCode === 13 && event.ctrlKey) {
        // 在此处执行Ctrl+回车键操作，例如换行
        var textarea = event.target;
        var startPos = textarea.selectionStart;
        var endPos = textarea.selectionEnd;
        var text = textarea.value;
        textarea.value = text.substring(0, startPos) + "\n" + text.substring(endPos, text.length);
        textarea.selectionStart = startPos + 1;
        textarea.selectionEnd = startPos + 1;
    }
}

function switchFoucus(_this, col) {
    switch (col) {
        case 1:
            let summaryInput = _this.parent().find(".summary-input");

            $(".voucher-body").off('keyup', ".summary-input").on('keyup', ".summary-input", function (ev) {
                if (ev.keyCode === 9) {
                    $("#bigAutocompleteContent").hide();
                    summaryInput.trigger('blur');
                    //Tab键切换焦点
                    let subjectContent = _this.parent().parent().find(".subject-content")
                    if (!subjectContent.find(".subject-name").text()) {
                        subjectContent.trigger('click');
                    } else {
                        _this.parent().parent().find(".subject-name").trigger('click')
                    }
                }else if(ev.keyCode === 13 && ev.ctrlKey){

                }
                else if (ev.keyCode === 13 && !$("#bigAutocompleteContent .ct").length) {
                    enterFoucus(_this.parent().find(".summary"), 1)
                }
            })
            $(".voucher-body").off('keydown', ".summary-input").on('keydown', ".summary-input", function (ev) {
                handleTextareaKeyPress(ev);
            })
            break;
        case 2:
            let mxId = _this.parent().parent().find("[name='mxId[]']").val();
            let num = Number(_this.parent().parent().find("[name='voucherNum["+mxId+"]']").val());
            let currencyId = _this.parent().parent().find("[name='currencyId["+mxId+"]']").val();
            let subjectInput = _this.parent().find(".subject-input");
            $(".voucher-body").off('keyup', ".subject-input").on('keyup', ".subject-input", function (ev) {
                // 清空科目查询框时，弹窗科目选择
                if($(this).val() === ''){
                    _this.parent().parent().find("[name='subjectId["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='khid["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='supplierId["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='staffId["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='projectId["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='materialId["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='cashId["+mxId+"]']").val('')
                    _this.parent().parent().find("[name='departmentId["+mxId+"]']").val('')
                    selector(_this.parent());
                }
                if (ev.keyCode === 9) {
                    hideSelector();
                    hideAssetSelector();
                    subjectInput.trigger('blur');
                    //Tab键切换焦点
                    if (num !=0 || currencyId){
                        let numCol = _this.parent().parent().find(".num-col")
                        numCol.trigger('click');
                    }else{
                        let jie = _this.parent().parent().find(".jie")
                        jie.trigger('click');
                    }
                    $("#bigAutocompleteContent").find("tr").removeClass("ct");
                    $("#bigAutocompleteContent").hide();
                }
            })
            break;
        case 'jie-currency'://外币核算后触发到借方

            let jie = _this.find(".jie")
            jie.trigger('click');
            break;
        case 'dai-currency'://外币核算后触发到贷方
            let dai = _this.find(".dai")
            dai.trigger('click');
            break;
        case 3:
            _this.parent().find(".jie-input").trigger('blur');
            //Tab键切换焦点
            _this.parent().parent().find(".dai").trigger('click')
            break;
        default:
            _this.parent().find(".dai-input").trigger('blur');
            //Tab键切换焦点
            //1、判断是否还有下一行
            if (!_this.parent().parent().nextAll(".container-body-row").eq(0).hasClass("container-body-row")) {
                //没有下一行就自动新增一行
                addTr(_this);
            } else {
                _this.parent().parent().nextAll(".container-body-row").eq(0).find(".summary").trigger('click');
            }

            break;
    }
}

function addTr(_this) {
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=addRow', {}, function (res) {
        listCol();
        $(".voucher-flex-container .container-body-row:last").after(res.html);
        scrollBottom();
        _this.parent().parent().next(".container-body-row").find(".summary").trigger('click');
    }, 'json')
}

function requestSubject() {
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=getSubject', {}, function (res) {
        if (res.warn === 2) {
            subjectCollection = res.data;
            readySubject();
            $(".subject-tabs").empty().append(res.tabs);
        }
    }, 'json')
}


/**
 * 数量/外币核算确认
 */
function confirmCurrency() {
    let mxId = $("[name='currenyMxId']").val();
    let row = $("[data-id='" + mxId + "']").parent().parent();
    let jine = 0;
    if ($("[name='numAsset']").length > 0) {
        let num = Number($("[name='numAsset']").val());//数量
        let price = Number($("[name='priceAsset']").val());//单价
        row.find(".voucher-num-text").html(num.toFixed(2))
        row.find("[name='voucherNum[" + mxId + "]']").val(num.toFixed(2))
        row.find(".voucher-price-text").html(price.toFixed(4))
        row.find("[name='voucherPrice[" + mxId + "]']").val(price.toFixed(4));
        jine = (num * price).toFixed(2);
        row.find(".num-name").show();
    }
    if ($("[name='rateAsset']").length > 0) {
        let money = Number($("[name='moneyAsset']").val());//金额
        let rate = Number($("[name='rateAsset']").val());//汇率
        let currencyHiddenId = $("[name='currencyHiddenId']").val();
        let currencyHiddenName = $("[name='currencyHiddenName']").val();
        row.find(".voucher-money-btn").html(currencyHiddenName + '：')
        row.find(".voucher-money-text").html(money.toFixed(2))
        row.find("[name='voucherMoney[" + mxId + "]']").val(money.toFixed(2))
        row.find(".voucher-rate-text").html(rate.toFixed(4))
        row.find("[name='voucherRate[" + mxId + "]']").val(rate.toFixed(4))
        row.find("[name='currencyId[" + mxId + "]']").val(currencyHiddenId);
        jine = (money * rate).toFixed(2);
        row.find(".currency-name").show();
    }
    hideCurrency();
    if (row.find(".dai-input").val() != 0) {
        splitNumber(jine * 100,row.find(".dai-text"))
        row.find(".dai-input").val(jine)
        enterFoucus(row, 'dai-currency');
    } else {
        splitNumber(jine * 100,row.find(".jie-text"))
        row.find(".jie-input").val(jine)
        enterFoucus(row, 'jie-currency');
    }
}

/**
 * 显示数量/外币核算弹窗
 */
function showCurrency(e, json) {
    let _this = $(e);
    $.post(root + "control/adIndex.html?cla=voucherEdit&fun=getCurrencyAssit", json, function (data) {
        $(".currency-assit .currency-assit-ul").children().remove();
        $(".currency-assit .currency-assit-ul").append(data.html);
        let selector = $(".currency-assit");
        let h = _this.outerHeight();
        let offset = _this.offset();
        let scrollTop = $("#body").scrollTop();
        selector.css({"top": scrollTop + offset.top + h - 38, "left": offset.left+1});
        selector.show();
        selector.find("input:first").focus().select();
    }, "json");
}

/**
 * 关闭数量/外币核算弹窗
 */
function hideCurrency() {
    $(window).off('keyup');
    $(".currency-assit .currency-assit-ul").children().remove();
    $(".currency-assit").hide();
}
/**
 * 显示辅助核算填写框
 */
function showAssetSelector(e, json,source='') {
    let _this = $(e);
    let cell = _this.parent();
    //
    // cell.find(".subject-input").off('input').on('input',function(ev) {
    //
    // });
    $.post(root + "control/adIndex.html?cla=voucherEdit&fun=getAssit", json, function (data) {
        $(".subject-selector").after(data.html);
        let selector = $(".voucher-body .auxiliary-accounting");
        let voucherBodyPaddingTop = $(".voucher-body").css("padding-top").replace('px','')
        selector.width(cell.outerWidth()-20)
        let h = cell.outerHeight();
        let offset = cell.offset();
        let scrollTop = $("#body").scrollTop();
        selector.css({"top": scrollTop + offset.top + h - voucherBodyPaddingTop-28, "left": offset.left+1});
        if (source ==='enter'){
            selector.find("input:first").focus();
        }
    }, "json");
}

function hideAssetSelector() {
    $(window).off('keyup');
    $(".voucher-body .auxiliary-accounting").remove();
}

/**
 * 显示科目选择器
 */
function selector(cell) {
    hideAssetSelector();
    let _this = $(cell);

    let textarea = _this.find(".subject-input");
    let holdText = textarea.val();//输入框原始值
    subjectSelectCurrent = textarea;
    let width = _this.outerWidth();
    let offset = _this.offset();
    let selectorObject = $(".subject-selector");
    selectorObject.width(width);
    let h = _this.outerHeight();
    let scrollTop = $("#body").scrollTop();
    selectorObject.css({"top": scrollTop + offset.top + h - 38, "left": offset.left+1});
    subjectSelectTop = scrollTop + offset.top + h - 28;
    $(".subject-tabs .tab-item:first").addClass('active').siblings().removeClass('active');
    readySubject()
    selectorObject.show();
    let $bigAutocompleteContent = selectorObject;
    let subjectBox = $bigAutocompleteContent.find(".subject-box");

    //输入框keyup事件
    subjectSelectCurrent.off('keyup').keyup(function (event) {
        switch (event.keyCode) {
            case 40://向下键
                if ($bigAutocompleteContent.css("display") === "none") return;
                let $nextSiblingTr = $bigAutocompleteContent.find(".ct");
                if ($nextSiblingTr.length <= 0) {//没有选中行时，选中第一行
                    $nextSiblingTr = $bigAutocompleteContent.find(".subject-item:first");
                } else {
                    $nextSiblingTr = $nextSiblingTr.next();
                }
                $bigAutocompleteContent.find(".subject-item").removeClass("ct");
                if ($nextSiblingTr.length > 0) {//有下一行时（不是最后一行）
                    $nextSiblingTr.addClass("ct");//选中的行加背景
                    // _this.val($nextSiblingTr.html());//选中行内容设置到输入框中
                    //div滚动到选中的行,jquery-1.6.1 $nextSiblingTr.offset().top 有bug，数值有问题
                    subjectBox.scrollTop($nextSiblingTr[0].offsetTop - subjectBox.height() + $nextSiblingTr.height());
                } else {
                    textarea.val(holdText);//输入框显示用户原始输入的值
                }
                break;
            case 38://向上键
                if ($bigAutocompleteContent.css("display") === "none") return;
                let $previousSiblingTr = $bigAutocompleteContent.find(".ct");
                if ($previousSiblingTr.length <= 0) {//没有选中行时，选中最后一行行
                    $previousSiblingTr = $bigAutocompleteContent.find(".subject-item:last");
                } else {
                    $previousSiblingTr = $previousSiblingTr.prev();
                }
                $bigAutocompleteContent.find(".subject-item").removeClass("ct");
                if ($previousSiblingTr.length > 0) {//有上一行时（不是第一行）
                    $previousSiblingTr.addClass("ct");//选中的行加背景
                    // _this.val($previousSiblingTr.html());//选中行内容设置到输入框中
                    //div滚动到选中的行,jquery-1.6.1 $$previousSiblingTr.offset().top 有bug，数值有问题
                    subjectBox.scrollTop($previousSiblingTr[0].offsetTop - subjectBox.height() + $previousSiblingTr.height());
                } else {
                    textarea.val(holdText);//输入框显示用户原始输入的值
                }
                break;
            case 27://ESC键隐藏下拉框
                hideSelector();
                break;
            case 13:
                event.preventDefault();
                if ($bigAutocompleteContent.css("display") !== "none") {
                    let ct = $bigAutocompleteContent.find(".ct");
                    subjectItemCallback(ct,'enter');
                }
                break;
            default:
                if (event.keyCode === 8){
                    let numCell = cell.parent().find(".num-col");
                    //当科目栏输入框中内容有变化，则清楚掉之前选中的科目，辅助核算和外币核算
                    cell.find(".subject-content").attr('data-asset','');
                    cell.find(".subject-content input").val('');
                    numCell.find(".voucher-money-btn").html('');
                    numCell.find(".voucher-money-text").html('');
                    numCell.find(".voucher-rate-text").html('');
                    numCell.find(".voucher-price-text").html('');
                    numCell.find(".voucher-num-text").html('');
                    numCell.find("input").val('');
                    numCell.find(".num-name").hide();
                    numCell.find(".currency-name").hide();
                    selector(cell)
                }
                if (!functionalKeyArray.includes(event.keyCode)) {
                    readySubject(textarea.val());
                }
                break;

        }
    });
}

/**
 * 隐藏科目选择器
 */
function hideSelector() {
    subjectSelectCurrent = null;
    $(".subject-selector").hide();
}

function accountMx(event,e) {
    let row = $(e).parent().parent().parent().parent();
    let mxId = row.find("[name='mxId[]']").val();
    let subjectId = row.find("[name='subjectId[" + mxId + "]']").val();
    newIframe('明细账', root + 'control/adIndex.html?cla=accountDetails&fun=home&id=' + subjectId);
    event.stopPropagation();
    return false;
}

/**
 * 根据判断当前借贷行数是否相等从而判断是否需要自动增加行数
 * @param _this
 * @param _that
 * @param direction
 */
function autoAddRow(_this, _that, direction) {
    let row = _this.parent().parent();//
    let cell = _this.parent();
    let otherSideMoney = 0;
    if (direction ==='借'){
        otherSideMoney = Number(row.find(".dai-input").val());
    }else{
        otherSideMoney = Number(row.find(".jie-input").val());
    }
    if (Number(cell.find("input").val()) == 0 && otherSideMoney == 0){
        if (direction ==='借'){
            enterFoucus(_this, 3)
        }else{
            enterFoucus(row.find(".jie"), 3)
        }
        return true;
    }

    //判断是否需要自动增加1列
    let daiNum = 0;
    let daiMoney = 0;
    let daiInputClass = $(".dai-input");
    daiInputClass.each(function () {
        let inputValue = +$(this).val();
        if (inputValue != 0) {
            daiNum++;
        }
        daiMoney += inputValue;
    });
    let jieMoney = 0;
    let jieInputClass = $(".jie-input");
    let jieNum = 0;
    jieInputClass.each(function () {
        let inputValue = +$(this).val();
        if (inputValue != 0) {
            jieNum++;
        }
        jieMoney += inputValue;
    });
    let summary = _this.parent().parent().find(".summary-input").val();
    if (jieMoney != daiMoney) {
        $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=addRow', {
            jieNum: jieNum,
            daiNum: daiNum,
            jieMoney: jieMoney,
            daiMoney: daiMoney,
            direction: direction,
            summary: summary
        }, function (res) {
            _this.parent().parent().after(res.html);
            listCol();
            scrollBottom();
            // _that.trigger('blur');
            if (direction === '贷') {
                enterFoucus(_this, 4)
            } else {
                enterFoucus(_this, 3, 1)
            }
            total_money();

        }, 'json')
    } else {
        // _that.trigger('blur');
        if (direction === '贷') {
            enterFoucus(_this, 4)
        } else {
            enterFoucus(_this, 3,1)
        }
    }
}

//切换凭证字获取当前凭证号
function changeVoucherWordId(e) {
    let voucherWordId = $("[name='voucherWordId']").val();
    let recordDate = $("[name='recordDate']").val();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=getVoucherNo', {
        voucherWordId: voucherWordId,
        recordDate: recordDate
    }, function (res) {
        $("#voucherNo").val(res.voucherNo);
    }, 'json')
}

//获取汇率
function getRate(e) {
    let id = $(e).val();
    let row = $(e).parent().parent().parent();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=getRate', {id: id}, function (res) {
        row.find(".voucher-rate-text").text(res.data);
        row.find(".voucher-rate-input").val(res.data);
        //计算单价
        let num = Number(row.find(".voucher-num-input").val());//数量
        let rate = Number(res.data);//汇率
        let money = Number(row.find(".voucher-money-input").val());//原币
        let price = num > 0 ? (money * rate / num).toFixed(4) : 0
        row.find(".voucher-price-input").val(price);
        row.find(".voucher-price-text").html(price)
        calculateBaseMoney(row.parent());//计算本位币总金额
    }, 'json')
}

//合计金额
function total_money() {
    let jieMoney = 0;
    $(".jie-input").each(function () {
        jieMoney += Number($(this).val());
    })
    $(".upper-money-total>span").html(upperMoney(jieMoney))
    splitNumber((jieMoney * baseUnit).toFixed(0),$(".jie-total"))
    let daiMoney = 0;
    $(".dai-input").each(function () {
        daiMoney += Number($(this).val());
    })
    splitNumber((daiMoney * baseUnit).toFixed(0),$(".dai-total"))
}

//计算本位币总金额
function calculateBaseMoney(tdObj) {
    let num = Number(tdObj.find(".voucher-num-input").val());//数量
    let price = Number(tdObj.find(".voucher-price-input").val());//单价
    splitNumber((num * price).toFixed(2) * baseUnit,tdObj.parent().find(".jie-text"))
    tdObj.parent().find(".jie-input").val((num * price).toFixed(2));
    total_money();
}

//辅助核算确认
function confirmAssist(mxId, subjectId, isCurrency,subjectName) {
    let assetTitle = '';
    let id = '';
    let flag = false;
    let list = 0;
    let objType = '';
    let idArr = [];
    let row = $("[data-id='" + mxId + "']").parent().parent();
    $(".voucher-body .auxiliary-accounting").find("input[type='text']").each(function (index) {
        if (!$(this).val()) {
            msg('请选择完辅助核算', 'error');
            flag = true;
            return false;
        }
        id = $(this).data('id')
        idArr.push(id);
        list++;
        objType = $(this).data('type');
        row.find("[name='" + objType + "[" + mxId + "]']").val(id);
        if (index > 0) {
            assetTitle += '_';
        }
        assetTitle += $(this).val()
    })
    if (flag) {
        return false;
    }
    idArr = idArr.sort();
    // row.find(".assist-name").show();
    // row.find(".assist-name").html(str);
    row.find(".subject-name").html(subjectName+' '+assetTitle);
    row.find(".subject-input").val(subjectName+' '+assetTitle)
    row.find(".subject-content").attr('data-asset', idArr.join(','));
    culBalance(subjectId, mxId);
    hideAssetSelector();
    if (isCurrency === '是') {
        let num = Number(row.find("[name='voucherNum["+mxId+"]']").val());
        let currencyId = row.find("[name='currencyId["+mxId+"]']").val();
        let price = Number(row.find("[name='voucherPrice["+mxId+"]']").val());
        let rate = Number(row.find("[name='voucherRate["+mxId+"]']").val());
        let money = Number(row.find("[name='voucherMoney["+mxId+"]']").val());
        showCurrency(row.find(".num-col"), {
            subjectId: subjectId,
            mxId: mxId,
            num:num,
            price:price,
            currencyId:currencyId,
            money:money,
            rate:rate,
        })
    } else {
        enterFoucus(row.find(".subject-content"), 2);
    }
}

function chooseTemplate() {
    let templateId = $("form[name='mxForm'] [name='templateId']:checked").val();
    if (!templateId) {
        msg('请选择模板', 'error');
        return false;
    }
    $('#voucherEditTemplate').hide()
    location.href = root + 'control/adIndex.html?cla=voucherEdit&fun=home&method=template&id=' + templateId;
}

function chooseSubjectId(e) {
    let id = $(e).data('id');
    let name = $(e).data('name');
    $(e).parent().find("li").css('background-color', 'white');
    $(e).css('background-color', "rgb(242, 242, 242)");
    $("[name='chooseId']").val(id);
    $("[name='chooseName']").val(name);
}

//获取科目信息
function chooseSubject(id, mxId,source='') {
    subjectRequest(id, mxId,source);
}

//在弹窗选择科目时确认
function confirmSubjectId(mxId) {
    let id = $("[name='chooseId']").val();
    subjectRequest(id, mxId);
    $('#voucherEditSubject').hide()
}

function subjectRequest(id, mxId,source='') {

    if (!id || !mxId) {
        // msg('未找到ID','error')
        return false;
    }
    let row = $("[data-id='" + mxId + "']").parent().parent();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=subjectInfo', {id: id}, function (res) {
        if (res.warn === 2) {
            row.find(".subject-name").html(res.data.code + ' ' + res.data.name);
            row.find(".assist-name").html('');
            row.find(".voucher-num-text").html('');
            row.find(".voucher-price-text").html('');
            row.find("[name='subjectId[" + mxId + "]']").val(res.data.id)
            row.find("[name='khid[" + mxId + "]']").val('');
            row.find("[name='voucherPrice[" + mxId + "]']").val('');
            row.find("[name='supplierId[" + mxId + "]']").val('')
            row.find("[name='voucherNum[" + mxId + "]']").val('')
            row.find("[name='staffId[" + mxId + "]']").val('')
            row.find("[name='projectId[" + mxId + "]']").val('')
            row.find("[name='materialSkuId[" + mxId + "]']").val('')
            row.find("[name='cashId[" + mxId + "]']").val('')
            row.find("[name='departmentId[" + mxId + "]']").val('')
            // row.find(".balance").show();
            // row.find(".balance-money").html(res.data.balanceMoney);
            culBalance(id, mxId);
            // row.find(".subject-input").html(res.data.code +' '+ res.data.name);
            row.find(".subject-input").val(res.data.code + ' ' + res.data.name);
            if (res.data.assistAccount === '是') {
                let khid = row.find("[name='khid[" + mxId + "]']").val();
                let supplierId = row.find("[name='supplierId[" + mxId + "]']").val();
                let departmentId = row.find("[name='departmentId[" + mxId + "]']").val();
                let materialSkuId = row.find("[name='materialSkuId[" + mxId + "]']").val();
                let staffId = row.find("[name='staffId[" + mxId + "]']").val();
                let cashId = row.find("[name='cashId[" + mxId + "]']").val();
                let projectId = row.find("[name='projectId[" + mxId + "]']").val();
                showAssetSelector(row.find(".subject-content"), {
                    mxId: mxId,
                    subjectId: id,
                    khid: khid,
                    supplierId: supplierId,
                    departmentId: departmentId,
                    materialSkuId: materialSkuId,
                    staffId: staffId,
                    cashId: cashId,
                    projectId: projectId
                },source)
            } else if (res.data.currencyAccount === '是' || res.data.numAccount === '是') {
                let num = Number(row.find("[name='voucherNum["+mxId+"]']").val());
                let currencyId = row.find("[name='currencyId["+mxId+"]']").val();
                let price = Number(row.find("[name='voucherPrice["+mxId+"]']").val());
                let rate = Number(row.find("[name='voucherRate["+mxId+"]']").val());
                let money = Number(row.find("[name='voucherMoney["+mxId+"]']").val());
                showCurrency(row.find(".num-col"), {
                    mxId: mxId,
                    subjectId: id,
                    num:num,
                    price:price,
                    currencyId:currencyId,
                    money:money,
                    rate:rate,
                })
            }
            if (res.data.currencyAccount === '否' && res.data.numAccount === '否'){
                //没有外币和金额辅助核算的时候就隐藏
                row.find(".num-name").hide();
                row.find(".currency-name").hide();
                row.find("[name='voucherMoney["+mxId+"]']").val('');
                row.find("[name='voucherRate["+mxId+"]']").val('');
                row.find("[name='currencyId["+mxId+"]']").val('');
                row.find("[name='voucherNum["+mxId+"]']").val('');
                row.find("[name='voucherPrice["+mxId+"]']").val('');
            }
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

/**
 * 计算余额
 */
function culBalance(subjectId, mxId) {
    if (!subjectId || !mxId) {
        return '';
    }
    let dataIdObj = '';
    let jieMoney = 0;
    let daiMoney = 0;
    let attrId = '';
    let obj = $("[data-id='" + mxId + "']").parent().parent();
    let assetIds = obj.find(".subject-content").attr('data-asset');
    $(".voucher-flex-container input[data-id]").each(function (e) {
        dataIdObj = $(this).parent().parent();
        attrId = dataIdObj.find("[name='mxId[]']").val();
        let attrAssetIds = dataIdObj.find(".subject-content").attr('data-asset');
        if ((dataIdObj.find("[name='subjectId[" + attrId + "]']").val()) === subjectId && assetIds == attrAssetIds) {
            //查找相同科目和相同辅助核算ID的项，把金额相加实时算出余额
            jieMoney += Number(dataIdObj.find("[name='jieMoney[" + attrId + "]']").val());
            daiMoney += Number(dataIdObj.find("[name='daiMoney[" + attrId + "]']").val());
        }
    })
    let recordDate = $("[name='recordDate']").val();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=culBalance', {
        recordDate: recordDate,
        id: subjectId,
        mxId: mxId,
        jieMoney: jieMoney,
        daiMoney: daiMoney,
        idCollection: assetIds
    }, function (res) {
        if (res.warn == 2) {
            $(".voucher-flex-container input[data-id]").each(function (e) {
                dataIdObj = $(this).parent().parent();
                attrId = dataIdObj.find("[name='mxId[]']").val();
                let attrAssetIds = dataIdObj.find(".subject-content").attr('data-asset');
                if ((dataIdObj.find("[name='subjectId[" + attrId + "]']").val()) === subjectId && assetIds == attrAssetIds) {
                    dataIdObj.find(".balance").show();
                    dataIdObj.find(".balance-money").html(res.data.balanceMoney);
                }
            })
            balanceColor();
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

function saveFile(formName) {
    let html = '';
    let val = '';
    $("form[name='" + formName + "'] [name='fileId[]']").each(function () {
        val = $(this).val();
        html += "<input name='fileId[]' type='hidden' value='" + val + "'>";
    })
    $("#file-list").empty().append(html);
    $('#voucherEditAttachFile').hide()
}

function voucherNumEdit(form, url) {
    let con = setTimeout(function () {
        $("#loading", window.top.document).hide();
    }, 15000);
    $("#loading", window.top.document).show();
    //串联表单
    var formName = form.split(",");
    var serialize = "";
    var a = "";
    for (var i = 0; i < formName.length; i++) {
        if (serialize == "") {
            a = "";
        } else {
            a = "&";
        }
        if (formName[i] != "") {
            serialize += a + $("[name=" + formName[i] + "]").serialize();
        }
    }
    //异步提交数据
    $.post(url, serialize, function (res) {
        $("#loading", window.top.document).hide();
        clearTimeout(con);
        if (res.warn === 2) {
            $('#voucherEditVoucherNumAdd').hide()
            if (res.data.fontSize) {
                $(".voucher-body").css('font-size', res.data.fontSize + 'px');
                $(".voucher-flex-container textarea").css('font-size', res.data.fontSize + 'px');
                msg(res.msg);
            }
            $(".calendarBody").data('r',res.data.rateAndMoney);
            $(".calendarBody").data('n',res.data.numAndPrice);
        } else {
            warn(res.warn, 'error');
        }

    }, "json");

}

function commitPhotograph(form, url) {
    let con = setTimeout(function () {
        $("#loading", window.top.document).hide();
    }, 15000);
    $("#loading", window.top.document).show();
    //串联表单
    var formName = form.split(",");
    var serialize = "";
    var a = "";
    for (var i = 0; i < formName.length; i++) {
        if (serialize == "") {
            a = "";
        } else {
            a = "&";
        }
        if (formName[i] != "") {
            serialize += a + $("[name=" + formName[i] + "]").serialize();
        }
    }
    //异步提交数据
    $.post(url, serialize, function (data) {
        if (data.warn == 2) {
            $('#voucherEditPhotograph').hide();
            $("#file-list").empty().append(data.html);
        } else {
            warn(data.warn, 'error');
        }
        $("#loading", window.top.document).hide();
        clearTimeout(con);
    }, "json");
}

//原始文件拍照
function photograph() {
    $('#voucherEditAttachFile').hide()
    layer('voucherEdit', 'photograph', {})
}

function setXformClass() {
    $('.xform').each(function (idx, el) {
        el.className = "xform x" + "-rotated-" + phi;
    });
}

// 旋转
function roateImg() {
    phi = (phi + 90) % 360;
    setXformClass();
    if (phi % 180) {
        $('.xform-p').addClass('rotated');
    } else {
        $('.xform-p').removeClass('rotated');
    }
}

function delImg(e) {
    $(e).parent().remove()
}

//拍照
function GrabImageBase64() {

    var cutpage = document.getElementsByName("cutpage");
    var params = "{\"filepath\":\"base64\",\"rotate\":\"" + phi.toString() + "\",\"camidx\":\"" + camidx.toString() + "\",\"cutpage\":\"" + (cutpage[0].checked ? "1" : "0") + "\"}";//
    var url = "http://127.0.0.1:38088/video=grabimage";
    $.ajax({
        type: "post",
        url: url,
        dataType: "json",
        data: params,
        success: function (data) {
            $(".picture-list").append("<div style='padding:10px;position:relative'><img class='li-ico' style='width:200px' src='data:image/jpg;base64," + data.photoBase64 + "'><a style='position:absolute;top: 2px;right: 72px;' onclick='delImg(this)' href='javascript:void(0)'><div style='top:0;left:0'><span class='u-icon-delete'><i></i></span></div></a><input name='fileCode[]' type='hidden' value='data:image/jpg;base64," + data.photoBase64 + "'></div>")
        }
    });
}

//初始化
function Init() {
    GetResolution();
}

function GetResolution() {
    var params = "{\"type\": \"resolution\",\"camidx\":\"" + camidx.toString() + "\"}";//
    var url = "http://127.0.0.1:38088/param=get";
    $.ajax({
        type: "post",
        url: url,
        dataType: "json",
        data: params,
        success: function (data) {
            if (data.code != 0) {
                console.log("返回代码 = " + data.code + "<br />返回信息 = " + data.message)
            } else {
                var select = document.getElementById("resolution");
                //获取select下拉框下所有的选项
                while (select.options.length > 0) {
                    select.remove(i);
                }

                var arrays = data.resolution.split("|");
                for (var i = 0; i < arrays.length; i++) {
                    select.options.add(new Option(arrays[i], arrays[i]));
                }
            }
        }
    });
}

function showSubjectSelector(e) {
    let id = $(e).parent().parent().parent().find("[name='mxId[]']").val();
    layer('voucherEdit', 'subject', {mxId: id});
    setTimeout(function () {
        $(e).hide();
    }, 1000)
}

/**
 * 旧版
 */
function flushSubjuct() {
    $('#voucherEditSubjectTempAdd').hide()
    requestSubject();
    if ($.cookie('warn')) {
        warn($.cookie('warn'));
        $.cookie('warn', '');
    }
}

/**
 * 模板类型编辑
 */
function commitTemp() {
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=templateTypeEdit', {type: $("[name='typeName']").val()}, function (res) {
        if (res.warn === 2) {
            $('#voucherEditTemplateType').hide();
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

/**
 * 余额为负数时设置自提颜色为红色
 */
function balanceColor() {
    $(".balance-money").each(function () {
        let money = Number($(this).html());
        if (money < 0) {
            $(this).css('color', 'red');
        } else {
            $(this).css('color', 'black');
        }
    })
}

/**
 * 初始化科目选择
 */
function readySubject(_keyword, data = null) {
    data = data ? data : subjectCollection.all;
    $(".subject-box").empty();
    for (let i = 0; i < data.length; i++) {
        if (!_keyword || (_keyword && data[i].title.indexOf(_keyword) > -1)) {
            let item = data[i];
            $(".subject-box").append(`<div class="subject-item" data-numasset="${item.numAccount}" data-auxiliary="${item.assistAccount}" data-currency="${item.currencyAccount}" data-id="${item.id}" data-name="${item.value}">${item.title}</div>`);
        }
    }
}

/**
 * 点击科目后触发的事件
 */
function subjectItemCallback(_this,source='') {
    let subjectId = _this.data('id');
    let name = _this.data('name');
    let cell = subjectSelectCurrent.parent().parent();
    let mxId = cell.parent().find("[name='mxId[]']").val();
    if (source === 'enter' && !subjectId){
        subjectId = cell.parent().find("[name='subjectId["+mxId+"]']").val();
        chooseSubject(subjectId, mxId,source);
        if (!cell.find(".subject-content").data('asset')){
            enterFoucus(cell.find(".subject-content"), 2)
        }
    }else{
        subjectSelectCurrent.val(name);
        cell.find(".subject-name").html(name);
        cell.find("[name='subjectId[" + mxId + "]']").val(subjectId);
        chooseSubject(subjectId, mxId,source);
        subjectSelectCurrent.hide();
        if (_this.data('auxiliary') === '否' && _this.data('numasset') === '否' && _this.data('currency') === '否'){
            enterFoucus(cell.find(".subject-content"), 2)
        }
    }
    hideSelector();
}

/**
 * 金额校验
 * @param value
 * @param num
 * @returns {*}
 */
function moneyCheck(value, num = 2) {
    value = value.replace(/[^\d.-]/g, ""); // 清除"数字"、"."和"-"以外的字符
    value = value.replace(/^\./g, ""); // 验证第一个字符是数字而不是字符
    value = value.replace(/\.{2,}/g, "."); // 只保留第一个.清除多余的
    value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    var negative = false;
    if (value.startsWith("-")) {
        negative = true;
        value = value.slice(1); // 去除负号
    }
    value = value.replace(new RegExp(`^(\\d+)\\.(\\d{${num}}).*$`), '$1.$2'); // 只能输入两个小数
    if (negative) {
        value = "-" + value; // 添加负号
    }
    return value;
}

function getSubjectCode(e) {
    let id = $(e).val();
    $.post(root + 'control/adIndex.html?cla=voucherEdit&fun=getSubjectCode', {id: id}, function (res) {
        if (res.warn === 2) {
            $("#subjectType").html(res.data.subject.type);
            $("[name='code']").val(res.data.code);
            $("[name='direction'][value='" + res.data.subject.direction + "']").prop("checked", true);
            $("#assistAccount").html(res.data.assitOption);
        } else {
            msg(res.warn, 'error')
        }
    }, 'json')
}

function chooseBox(e, id) {
    if ($(e).is(":checked")) {
        $("#" + id).show();
    } else {
        $("#" + id).hide();
    }
}

/**
 *
 * 保存结果
 */
function saveRes(mxId, type) {
    $('#voucherEditCalculator').hide()
    let parent = $("[name='mxId[]'][value='" + mxId + "']").parent().parent();
    if (type === 'jie') {
        let jieObj = parent.find(".jie");
        let jieInput = parent.find(".jie-input");
        jieInput.val(Number($("#calculatorValue").html()))
        jieInput.trigger('blur');
        jieObj.trigger('click');
    } else {
        let daiObj = parent.find(".dai");
        let daiInput = parent.find(".dai-input");
        daiInput.val(Number($("#calculatorValue").html()))
        daiInput.trigger('blur');
        daiObj.trigger('click');
    }
}

function scrollBottom() {
    var element = document.getElementById("container-body");
    element.scrollTop = element.scrollHeight;
}

/**
 * 辅助核算的输入框焦点
 */
function switchAssetInput(e) {
    let nextElement = $(e).parent().parent().next(".account-item");
    if (nextElement.length > 0) {
        nextElement.find("input").focus();
    }
}

/**
 * 切换数量/外币核算的输入框焦点
 */
function switchCurrenyInput(e) {
    let nextElement = $(e).parent().parent().next(".account-item");
    if ($(e).is("[name='priceAsset']") && nextElement.length > 0) {
        let price = Number($("[name='priceAsset']").val());
        let num = Number($("[name='numAsset']").val());
        nextElement.find("input").val((price * num).toFixed(2))
    }
    if (nextElement.length > 0) {
        nextElement.find("input").focus().select();
    } else {
        $(e).blur();
    }
}

/**
 * 生成序号
 */
function listCol() {
    $(".container-body .container-body-row .setting-col span").each(function (index) {
        $(this).html(index + 1)
    })
}

/**
 * 添加科目按钮方法
 */
function addSubject() {
    hideSelector();
    layer('voucherEdit', 'subjectTempAdd', {})
}

/**
 * 分割数字
 * @param number
 * @param targetContainer
 */
function splitNumber(number,targetContainer) {
    var numberString = number.toString();
    var numberDigits = numberString.split('').reverse();
    let index = 0;
    var html = '';
    $.each(numberDigits, function(i, digit) {
        if (i===1){
            html="<div class=\"format-line pink\">"+digit+"</div>"+html;
        }else if (i===4 || i===7){
            html="<div class=\"format-line l-blue\">"+digit+"</div>"+html;
        }else{
            html="<div class=\"format-line\">"+digit+"</div>"+html;
        }
        index++;
    });
    for (index;index<11;index++){
        if (index===1){
            html="<div class=\"format-line pink\"></div>"+html;
        }else if (index===4 || index===7){
            html="<div class=\"format-line l-blue\"></div>"+html;
        }else{
            html="<div class=\"format-line\"></div>"+html;
        }
    }
    targetContainer.empty().append(html)
}



function layerFun(data) {
    if (data.warn) {
        if (data.warn === 2) {
            if (data.href) {
                window.location.href = data.href;
            } else {
                window.location.reload();
            }
        } else {
            warn(data.warn);
        }
    } else {
        var id = $("#" + data.id);
        if (id.length == 0) {
            var searchFormId = "";
            if (typeof data.searchFormId != "undefined") {
                searchFormId = " searchFormId='" + data.searchFormId + "' ";
            }
            $("#body").append("<div id='" + data.id + "' layerId='" + data.id + "' " + searchFormId + ">" + data.html + "</div>");
        } else {
            if (id.attr('id') !== 'voucherEditAttachFile'){
                id.html(data.html);
            }
            id.css("display", "block");
        }
        move(data.id);
    }
}
